标签
工具
字数
1138 字
阅读时间
6 分钟
一、概述
FastJson 是阿里巴巴的开源JSON解析库,它可以解析 JSON 格式的字符串,支持将 Java Bean 序列化为 JSON 字符串,也可以从 JSON 字符串反序列化到 JavaBean。
1.1 优点
- 速度快 fastjson相对其他JSON库的特点是快,从2011年fastjson发布1.1.x版本之后,其性能从未被其他Java实现的JSON库超越。
- 使用广泛 fastjson在阿里巴巴大规模使用,在数万台服务器上部署,fastjson在业界被广泛接受。在2012年被开源中国评选为最受欢迎的国产开源软件之一。
- 测试完备 fastjson有非常多的testcase,在1.2.11版本中,testcase超过3321个。每次发布都会进行回归测试,保证质量稳定。
- 使用简单 fastjson的 API 十分简洁。
- 功能完备 支持泛型,支持流处理超大文本,支持枚举,支持序列化和反序列化扩展。
二、使用Demo
2.1 springboot将json处理框架替换为fastjson
依赖
groovy
compile 'com.alibaba:fastjson:1.2.70'配置
java
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.MapSerializer;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
/**
* springboot 默认json处理框架换成FastJson
* author Brack.zhu
* date 2019/3/22
*/
@Configuration
@EnableWebMvc
public class FastJsonConfigurer implements WebMvcConfigurer {
static {//FIXME sunwen 替换FastJson Map序列化(修改Map数据为WriteMapNullValue),Map的子类无法通过@JSONType设置序列化参数
MapSerializer.instance = new FastJsonMapSerializer();
JSON.DEFAULT_GENERATE_FEATURE |= SerializerFeature.WriteDateUseDateFormat.getMask();//设置全局时间序列化方式
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(FastJsonHelper.getFastJsonConverter());
}
}工具类
java
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.MapSerializer;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.ResponseEntityDecoder;
import org.springframework.cloud.openfeign.support.SpringDecoder;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
/**
* @Classname FastJsonHelper
* @Description 构建fastjsonhttp转换类
* @Date 2021/08/14 17:12
* @Created by wxp
*/
public class FastJsonHelper {
public static FastJsonHttpMessageConverter getFastJsonConverter() {
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
fastConverter.setFastJsonConfig(getFastJsonConfig());
//处理中文乱码问题
List<MediaType> fastMediaTypes = new ArrayList<>();
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
fastConverter.setSupportedMediaTypes(fastMediaTypes);
return fastConverter;
}
public static FastJsonConfig getFastJsonConfig(){
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setCharset(StandardCharsets.UTF_8);
fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
// fastJsonConfig.getSerializeConfig().put(Json.class, new SwaggerJsonSerializer());
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat, SerializerFeature.DisableCircularReferenceDetect);
// fastJsonConfig.setParseProcess(Extra.extraProcessor);
// fastJsonConfig.setSerializeFilters(Extra.extraFilter);
return fastJsonConfig;
}
}map序列化
java
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.MapSerializer;
import com.alibaba.fastjson.serializer.SerializerFeature;
import java.io.IOException;
import java.lang.reflect.Type;
public class FastJsonMapSerializer extends MapSerializer {
@Override
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features, boolean unwrapped) throws IOException {
features |= SerializerFeature.WriteMapNullValue.mask;//改写FastJson Map的序列化方式,Map的子类无法通过@JSONType设置序列化参数
super.write(serializer, object, fieldName, fieldType, features, unwrapped);
}
}2.2 SSM集成
SpringMVC框架中,默认使用的json序列化工具是jackson,我们需要在SpringMVM的配置文件中,配置消息转换器,由jackson切换到FastJson.
依赖
xml
<!-- FastJson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>配置
xml
<mvc:annotation-driven>
<mvc:message-converters register-defaults="false">
<!-- FastJson的消息转换器-->
<bean id = "fastJson" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<!-- FastJsonHttpMessageConverter类属性赋值-->
<property name="supportedMediaTypes">
<list>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>2.3 基本使用
依赖
xml
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>对象转换
java
// Java对象转JSON
String jsonStr = JSON.toJSONString(obj);
// JSON字符串转Java对象
User user = JSON.parseObject(jsonStr, User.class);三、常用功能
3.1 序列化反序列化
java
// 序列化对象 转成json字符串 入参可以为对象、集合
String jsonString = JSON.toJSONString(obj);
// 反序列化对象
Obj obj = JSON.parseObject(jsonString, Obj.class);
// 反序列化集合
List<Obj> list = JSON.parseArray(jsonString,Obj.class);
// 反序列化Map
Map<String,Obj> parse = JSON.parseObject(jsonString,new TypeReference<Map<String,Obj>>(){});3.2 序列化配置
java
// WriteMapNullValue 序列化为null的字段
// WriteNullStringAsEmpty 字段为null,序列化为""
// WriteNullNumberAsZero 字段为null,序列化为0
// WriteNullBooleanAsFalse 字段值为null 输出false
// WriteDateUseDateFormat 格式化日期格式
// PrettyFormat格式化输出
String jsonString = JSON.toJSONString(obj, SerializerFeature.枚举);3.3 注解使用
java
@JSonField
//该注解作用于方法上,字段上和参数上.可在序列化和反序列化时进行特性功能定制.
//- 注解属性 : name 序列化后的名字
//- 注解属性 : ordinal序列化后的顺序
//- 注解属性 : format 序列化后的格式
//- 注解属性 : serialize 是否序列化该字段
//- 注解属性 : deserialize 是否反序列化该字段
//- 注解属性 : serialzeFeatures 序列化时的特性定义
@JSonType
// 该注解作用于类上,对该类的字段进行序列化和反序列化时的特性功能定制.
//- 注解属性 : includes 要被序列化的字段.
//- 注解属性 : orders 序列化后的顺序.
//- 注解属性 : serialzeFeatures 序列化时的特性定义.